package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 登录判断
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.检查参数: 账号+密码  或者  设备号id  不为空
        if((StringUtils.isBlank(dto.getPhone()) || StringUtils.isBlank(dto.getPassword()))
        &&dto.getEquipmentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"登录或设备ID信息不存在");
        }
        //2. 如果包含账号(手机号)和密码
        if(StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())) {
            //2-1 使用手机号查询apUser
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //2-2 如果手机号正确,对比密码是否正确(密码加盐再加密)
            String FinalPass = DigestUtils.md5DigestAsHex((dto.getPassword()+apUser.getSalt()).getBytes());
            if(!FinalPass.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错哟");
            }
            //2-3 颁发token
            String token = AppJwtUtil.getToken(apUser.getId());
            Map map = new HashMap<>();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }
        //3. 如果使用的是设备id,密码直接置为0,加盐加密,颁发token,map中不添加user
        else {
            String token = AppJwtUtil.getToken(0);
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
